<?php
/**
 * @file
 * JavaScript for deed module.
 *
 * Usage:
 *  - A page that wants to use this JavaScript file should link to this file
 *    using the '<script></script>' tags once and only once.
 *
 * Parameter(s):
 *  - None.
 *
 * Global variable(s) set:
 *  - None.
 *
 * Global variable(s) unset:
 *  - None.
 *
 * Exception(s):
 *  - None.
 *
 * This file includes/requires:
 *  - h_greenindeed.php
 *  - h_deed.php
 *  - h_filter.php
 *  - php/h_jqui.php
 *  - h_facebook.php
 */

// header file(s) ==============================================================
require_once "h_greenindeed.php";
require_once "h_deed.php";
require_once "h_filter.php";
require_once $PATH_COMMON . "php/h_jqui.php";
require_once $PATH_COMMON . "php/h_facebook.php";


// implementation ==============================================================
?>
// <script> // to induce syntax highlighting on netbeans

// global variable(s) ----------------------------------------------------------
var deedDeleting = false;   //!< Flag indicating a pending delete.
var deedAdding   = false;   //!< Flag indicating a pending add.


// implementation --------------------------------------------------------------
/**
 * Initializes the deed module.
 */
function deed_init() {
  // tabs for add deed (jquery)
  $('#<?php echo ID_DIV_TABS ?>').tabs({
    collapsible: true,  // make tabs collapsible
    selected: -1        // collapse tabs by default
  });

  // onclick event binding for 'add' button (jquery)
  $('.<?php echo CSS_CLASS_BUTTON_ADD ?>').click(function () {
    if (true == deedAdding) {
      // the previous add is not completed yet
      return false;
    }
    // set add pending flag
    deedAdding = true;
    // add deed
    deed_add(this.id);
    return false;
  });
}

/**
 * Sets the message in the view deed DIV.
 *
 * @param msg
 *    The message to set.
 * @param ftn
 *    Callback function after new message is displayed.
 */
function deed_setViewDiv(msg, ftn) {
  // fade out (jquery)
  $("#<?php echo ID_VIEW_DIV ?>").fadeOut("<?php echo EFFECTS_SPEED ?>",
    function () {
      // set message
      $("#<?php echo ID_VIEW_DIV ?>").html(msg);
      // fade in
      $("#<?php echo ID_VIEW_DIV ?>").fadeIn("<?php echo EFFECTS_SPEED ?>",
        ftn
      );
    }
  );
}

/**
 * Loads view deed page.
 */
function deed_view() {
  // remove previous error message
  $("#<?php echo ID_VIEW_ERR_DIV ?>").hide();
  // show loading message
  $("#<?php echo ID_VIEW_INFO_MSG ?>").html("<?php echo MSG_LOAD ?>");
  $("#<?php echo ID_VIEW_INFO_DIV ?>").fadeIn("<?php echo EFFECTS_SPEED ?>");

  // prepare url
  var url = "deed_view.php?" + <?php echo JS_VAR_PARAMS_GET ?>;
  // prepare key-value pairs
  var keys   = new Array();
  var values = new Array();
  keys.push("<?php echo NAME_FILTER_FIELD_MASK ?>");
  values.push(filter_getMask());
  keys.push("<?php echo NAME_FILTER_FIELD_ROWSPP ?>");
  values.push(filter_getRowsPP());
  // send request
  ajaxSend(deed_show, AJAX_METHOD_POST, url, keys, values);
}

/**
 * Shows view deed page.
 */
var deedId; // TODO: There has to be a better way to pass the deed ID...
function deed_show() {
  // check if request completed
  if (AJAX_REQUEST_COMPLETED == xmlhttp.readyState) {
    // request completed => show result
    deed_setViewDiv(xmlhttp.responseText, function () {
      // initialize deed delete confirmation dialog
      $('#dialog').dialog({
        autoOpen: false,
        buttons: {
          "OK": function () {
            // delete deed
            deed_delete(deedId);
            $(this).dialog("close");
          },
          "Cancel": function () {
            // clear delete pending flag
            deedDeleting = false;
            $(this).dialog("close");
          }
        }
      });

      // hover event binding for 'delete' button (jquery)
      $(".<?php echo CSS_CLASS_BUTTON_DELETE ?>").hover(
        function () { $(this).addClass("<?php echo JQUI_CSS_CLASS_ICON ?>") },
        function () { $(this).removeClass("<?php echo JQUI_CSS_CLASS_ICON ?>") }
      );

      // onclick event binding for 'delete' button (jquery)
      $(".<?php echo CSS_CLASS_BUTTON_DELETE ?>").click(function () {
        // check if there is a pending delete
        if (true == deedDeleting) {
          // the previous delete is not completed yet
          return false;
        }
        // set delete pending flag
        deedDeleting = true;
        // set deed id
        deedId = this.id;
        // open confirmation dialog
        $('#dialog').dialog('open');
        return false;
      });

      // resize iframe
      <?php require $PATH_COMMON . "php/fb_js_iframe_resize.js.php" ?>
    });
  }
}

/**
 * Sends delete deed request.
 *
 * @param idDeed
 *    Deed ID of the deed to delete.
 */
function deed_delete(idDeed) {
  // remove previous error message
  $("#<?php echo ID_VIEW_ERR_DIV ?>").hide();
  // show deleting deed message
  $("#<?php echo ID_VIEW_INFO_MSG ?>").html("<?php echo LBL_DEED_DELETING?>");
  $("#<?php echo ID_VIEW_INFO_DIV ?>").fadeIn("<?php echo EFFECTS_SPEED ?>");

  // prepare url
  var url = "deed_action_delete.php?" + <?php echo JS_VAR_PARAMS_GET ?>;
  // prepare key-value pairs
  var keys   = new Array();
  var values = new Array();
  keys.push("<?php echo ID_FIELD_ID_DEED ?>");
  values.push(idDeed);
  // send request
  ajaxSend(deed_deleted, AJAX_METHOD_POST, url, keys, values);
}

/**
 * Removes a deleted row. Clears the "deedDeleting" flag.
 */
function deed_deleted() {
  // check if request completed
  if (AJAX_REQUEST_COMPLETED == xmlhttp.readyState) {
    // request completed

    // check status is ok
    var errMsg = null;
    if (AJAX_STATUS_OK == xmlhttp.status) {
      // status ok

      // retreive response
      var response = xmlhttp.responseText.split(
        "<?php echo DELIMITER_DEED_ACTION_RESPONSE ?>"
      );
      // check whether delete was successful
      if (<?php echo DEED_ACTION_OK ?>
        == response[<?php echo DEED_DELETE_POS_FLAG ?>]) {
        // deletion ok

        // remove deleting deed message
        $("#<?php echo ID_VIEW_INFO_MSG ?>").fadeOut(
          "<?php echo EFFECTS_SPEED ?>",
          function () {
            // show deed deleted message
            $("#<?php echo ID_VIEW_INFO_MSG ?>").html(
              "<?php echo LBL_DEED_DELETED ?>"
            );
            $("#<?php echo ID_VIEW_INFO_MSG ?>").fadeIn(
              "<?php echo EFFECTS_SPEED ?>",
              function () {
                // get row id
                var idRow = "<?php echo ID_VIEW_TR_PREFIX ?>"
                          + response[<?php echo DEED_DELETE_POS_DEED_ID ?>];
                // animate row removal (jquery)
                $("#" + idRow).fadeOut("<?php echo EFFECTS_SPEED ?>",
                  function() {
                    // delete row from table
                    $(this).remove();
                    // remove deed deleted message
                    $("#<?php echo ID_VIEW_INFO_DIV ?>").fadeOut(
                      "<?php echo EFFECTS_SPEED ?>"
                    );
                  }
                );
              }
            );
          }
        );
      } else {
        // deletion failed
        errMsg = response[<?php echo DEED_DELETE_POS_ERROR_MSG ?>];
      }
    } else {
      // status not ok
      errMsg = xmlhttp.status + ": " + xmlhttp.statusText;
    }

    if (null != errMsg) {
      // an error occured

      // remove message DIV
      $("#<?php echo ID_VIEW_INFO_DIV ?>").hide();
      // show error message
      $("#<?php echo ID_VIEW_ERR_MSG ?>").html(errMsg);
      $("#<?php echo ID_VIEW_ERR_DIV ?>").fadeIn(
        "<?php echo EFFECTS_SPEED ?>"
      );
    }
    // clear delete pending flag
    deedDeleting = false;
  }
}

/**
 * Adds a deed.
 *
 * @param deedTypeId
 *    Deed type ID.
 */
function deed_add(deedTypeId) {
  // get the form object
  var foAdd = eval(
    "document.<?php echo NAME_DEED_ADD_FORM_PREFIX ?>" + deedTypeId
  );
  // get user input
  var field, value;
  var stringInput   = "";
  var stringPublish = foAdd.<?php echo NAME_DEED_ADD_STATEMENT ?>.value;
  var arraySearch   = foAdd.<?php echo NAME_DEED_ADD_STATEMENT_SEARCH ?>
                      .value.split("<?php echo DELIMITER_DEED_STATEMENT ?>");
  if (undefined != foAdd.<?php echo NAME_DEED_ADD_INPUT ?>.length) {
    // more than one input field
    for (var i = 0; i < foAdd.<?php echo NAME_DEED_ADD_INPUT ?>.length; i++) {
      // get value
      field = foAdd.<?php echo NAME_DEED_ADD_INPUT ?>[i];
      value = trim(field.value);
      // check value
      if ("" == value) {
        // value cannot be empty.
        alert("<?php echo LBL_DEED_TEXT_ERR_EMPTY ?>");
        field.focus();
        deedAdding = false;
        return false;
      }
      // append value to input string
      stringInput += "<?php echo DELIMITER_DEED_STATEMENT ?>" + value;
      // replace in publish string
      stringPublish = stringPublish.replace(arraySearch[i], value);
    }
    // remove first delimiter
    stringInput = stringInput.substring(1);
  } else {
    // only one input field

    // get value
    field = foAdd.<?php echo NAME_DEED_ADD_INPUT ?>;
    value = trim(field.value);
    // check value
    if ("" == value) {
      // value cannot be empty.
      alert("<?php echo LBL_DEED_TEXT_ERR_EMPTY ?>");
      field.focus();
      deedAdding = false;
      return false;
    }
    // append value to input string
    stringInput += value;
    stringPublish = stringPublish.replace(arraySearch[0], value);
  }
  // check the input string's length.
  if (<?php echo DEED_INPUT_LENGTH_MAX ?> < stringInput.length) {
    // input string too long
    alert("<?php echo LBL_DEED_TEXT_ERR_LONG ?>".replace(
      "<?php echo SEARCH_DEED_TEXT_ERR_LONG ?>",
      (parseInt(stringInput.length)
        - parseInt(<?php echo DEED_INPUT_LENGTH_MAX ?>))
    ));
    deedAdding = false;
    return false;
  }

  // remove previous error message
  $("#<?php echo ID_ADD_ERR_DIV ?>").hide();
  // show adding deed message
  $("#<?php echo ID_ADD_INFO_MSG ?>").html("<?php echo LBL_DEED_ADDING?>");
  $("#<?php echo ID_ADD_INFO_DIV ?>").fadeIn("<?php echo EFFECTS_SPEED ?>");

  // prepare url
  var url = "deed_action_add.php?" + <?php echo JS_VAR_PARAMS_GET ?>;
  // prepare key-value pairs
  var keys   = new Array();
  var values = new Array();
  keys.push("<?php echo NAME_DEED_ADD_TYPE_ID ?>");
  values.push(deedTypeId);
  keys.push("<?php echo NAME_DEED_ADD_INPUT ?>");
  values.push(stringInput);

  // check if user wants to publish green deed
  if (true == foAdd.<?php echo NAME_DEED_ADD_PUBLISH ?>.checked) {
    // prompt user to publish green deed
    var fb_pub_user_message = stringPublish;
    var fb_pub_attachments  = {
      'caption' : "<?php echo APP_DESCRIPTION ?>",
      'media'   : [
        {
          'type' : 'image',
          'src'  : '<?php echo FB_APP_IMG ?>',
          'href' : '<?php echo FB_APP_URL_CANVAS ?>'
        }
      ]
    };
    var fb_pub_action_links   = <?php echo PUBLISH_ACTION_LINKS ?>;
    var fb_pub_target_user_id = null;
    var fb_pub_message_prompt = "<?php echo PUBLISH_MESSAGE_PROMPT ?>";
    var fb_pub_callback       = null;
    var fb_pub_auto_publish   = null;
    <?php require $PATH_COMMON . "php/fb_js_publish.js.php" ?>
  }

  // send request
  ajaxSend(deed_added, AJAX_METHOD_POST, url, keys, values);
}

/*
 * Informs user the deed is added successfully. Clears the "deedAdding" flag.
 */
function deed_added() {
  if (AJAX_REQUEST_COMPLETED == xmlhttp.readyState) {
    // request completed

    // check status is ok
    var errMsg = null;
    if (AJAX_STATUS_OK == xmlhttp.status) {
      // status ok

      // retreive response
      var response = xmlhttp.responseText.split(
        "<?php echo DELIMITER_DEED_ACTION_RESPONSE ?>"
      );
      // check whether add was successful
      if (<?php echo DEED_ACTION_OK ?>
        == response[<?php echo DEED_ADD_POS_FLAG ?>]) {
        // add ok

        // show deed added message
        $("#<?php echo ID_ADD_INFO_MSG ?>").html(
          "<?php echo LBL_DEED_ADDED ?>"
        );
        $("#<?php echo ID_ADD_INFO_DIV ?>").fadeIn(
          "<?php echo EFFECTS_SPEED ?>", function () {
            // reload view if current user is selected
            if (0 != (filter_getMask() & <?php echo VAL_FILTER_YOURSELF ?>)) {
              deed_view();
            }
          }
        );
      } else {
        // add failed
        errMsg = response[<?php echo DEED_DELETE_POS_ERROR_MSG ?>];
      }
    } else {
      // status not ok
      errMsg = xmlhttp.status + ": " + xmlhttp.statusText;
    }

    if (null != errMsg) {
      // an error occured
      // remove message DIV
      $("#<?php echo ID_ADD_INFO_DIV ?>").hide();
      // show error message
      $("#<?php echo ID_ADD_ERR_MSG ?>").html(errMsg);
      $("#<?php echo ID_ADD_ERR_DIV ?>").fadeIn("<?php echo EFFECTS_SPEED ?>");
    }
    // clear add pending flag
    deedAdding = false;
  }
}

// </script> // to induce syntax highlighting on netbeans
